package com.example.exception;

import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 外键约束异常
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class ForeignKeyException extends RuntimeException {
    
    private final String entityType;
    private final String entityName;
    private final String operation;
    private final List<RelatedData> relatedData;
    private final String constraintName;
    
    public ForeignKeyException(String message, String entityType, String entityName, 
                             String operation, List<RelatedData> relatedData, String constraintName) {
        super(message);
        this.entityType = entityType;
        this.entityName = entityName;
        this.operation = operation;
        this.relatedData = relatedData;
        this.constraintName = constraintName;
    }
    
    public ForeignKeyException(String message, String entityType, String entityName) {
        this(message, entityType, entityName, "DELETE", null, null);
    }
    
    /**
     * 关联数据信息
     */
    @Data
    public static class RelatedData {
        private String type;          // 数据类型
        private String name;          // 数据名称
        private String description;   // 数据描述
        private Long count;           // 数据数量
        
        public RelatedData(String type, String name, String description, Long count) {
            this.type = type;
            this.name = name;
            this.description = description;
            this.count = count;
        }
        
        public RelatedData(String type, String name, String description) {
            this(type, name, description, 1L);
        }
    }
    
    /**
     * 创建用户外键约束异常
     */
    public static ForeignKeyException userConstraintViolation(String username, List<RelatedData> relatedData) {
        return new ForeignKeyException(
            "无法删除用户，存在关联数据",
            "user",
            username,
            "DELETE",
            relatedData,
            "fk_user_related_data"
        );
    }
    
    /**
     * 创建充值记录外键约束异常
     */
    public static ForeignKeyException rechargeConstraintViolation(String orderNo, List<RelatedData> relatedData) {
        return new ForeignKeyException(
            "无法删除充值记录，存在关联数据",
            "recharge",
            orderNo,
            "DELETE",
            relatedData,
            "fk_recharge_related_data"
        );
    }
    
    /**
     * 创建余额记录外键约束异常
     */
    public static ForeignKeyException balanceConstraintViolation(String balanceId, List<RelatedData> relatedData) {
        return new ForeignKeyException(
            "无法删除余额记录，存在关联数据",
            "balance",
            balanceId,
            "DELETE",
            relatedData,
            "fk_balance_related_data"
        );
    }
} 